package com.cryptoneedle.center.source.util;

import cn.hutool.v7.extra.spring.SpringUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.cryptoneedle.center.source.entity.metadata.Catalog;
import com.cryptoneedle.center.source.properties.SshProperties;
import com.cryptoneedle.center.source.service.SshManager;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>description:  </p>
 *
 * @author CryptoNeedle
 * @date 2025-07-24
 */
public class JdbcUtil {

    private static final Map<String, DruidDataSource> DATA_SOURCE_MAP = new ConcurrentHashMap<>();
    private static final Map<String, JdbcTemplate> JDBC_TEMPLATE_MAP = new ConcurrentHashMap<>();

    public static DruidDataSource initDataSource(Catalog catalog) {
        if (catalog == null) {
            throw new RuntimeException("[JdbcTemplateUtil] Catalog is null");
        }

        SshProperties sshProperties = SpringUtil.getBean(SshProperties.class);
        if (sshProperties == null) {
            throw new RuntimeException("[JdbcTemplateUtil] SshProperties is null");
        }

        SshManager sshManager = SpringUtil.getBean(SshManager.class);
        if (sshManager == null) {
            throw new RuntimeException("[JdbcTemplateUtil] SshManager is null");
        }

        return DATA_SOURCE_MAP.computeIfAbsent(catalog.jdbcKey().toString(), key -> {
            DruidDataSource dataSource = new DruidDataSource();
            // 基本配置
            dataSource.setDriverClassName(catalog.getDriverClass());
            dataSource.setUrl(catalog.dataSourceUrl(sshProperties, sshManager));
            dataSource.setUsername(catalog.getUserName());
            dataSource.setPassword(CryptoUtils.decrypt(catalog.getPassword()));
            dataSource.setConnectProperties(catalog.getDatabaseType().getDatabase().getProperties());
            // 连接池配置
            dataSource.setInitialSize(1);
            dataSource.setMinIdle(1);
            dataSource.setMaxActive(1);
            dataSource.setMaxActive(60000);
            // 连接有效性检测配置
            dataSource.setValidationQuery(catalog.getDatabaseType().getDatabase().getDatabaseValidSql());
            dataSource.setTestWhileIdle(true);
            dataSource.setTestOnBorrow(true);
            dataSource.setTestOnReturn(false);
            dataSource.setTimeBetweenEvictionRunsMillis(60000);
            // 其他配置
            dataSource.setPoolPreparedStatements(true);
            return dataSource;
        });
    }

    public static JdbcTemplate getJdbcTemplate(Catalog catalog) {
        String key = catalog.jdbcKey().toString();
        return JDBC_TEMPLATE_MAP.computeIfAbsent(key, k -> new JdbcTemplate(initDataSource(catalog)));
    }
}